package com.cskaoyan.scheduled;

import com.cskaoyan.bean.po.MarketCoupon;
import com.cskaoyan.bean.po.MarketCouponExample;
import com.cskaoyan.bean.po.MarketCouponUser;
import com.cskaoyan.bean.po.MarketCouponUserExample;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/09 11:41
 */
@EnableScheduling//开启定时任务
@Component//注册
public class ScheduledApplication {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Scheduled(cron = "0/10 * * * * ?")
    public void CheckCouponStatusScheduledTask() {
        //当前日期
        Date rightNowTime = new Date(System.currentTimeMillis());
        //首先检查coupon表中的数据有没有过时的
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.createCriteria()
                .andStatusEqualTo((short) 0)
                .andDeletedEqualTo(false)
                .andEndTimeLessThan(rightNowTime);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        //筛选出来的，全部修改
        MarketCoupon target = new MarketCoupon();
        //修改为已过期
        target.setStatus((short) 1);
        for (MarketCoupon marketCoupon : marketCoupons) {
            target.setId(marketCoupon.getId());
            marketCouponMapper.updateByPrimaryKeySelective(target);
            //这里打印提醒一下
            System.out.println("MarketCoupon 中 id 为"+target.getId()+"的coupon， 状态已经修改为已过期");
        }
        //同样操作market-coupon-user表
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.createCriteria()
                .andStatusEqualTo((short) 0)
                .andEndTimeLessThan(rightNowTime)
                .andDeletedEqualTo(false);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        MarketCouponUser userTarget = new MarketCouponUser();
        userTarget.setStatus((short) 2);
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            userTarget.setId(marketCouponUser.getId());
            marketCouponUserMapper.updateByPrimaryKeySelective(userTarget);
            System.out.println("MarketCouponUser 中 id 为"+target.getId()+"的coupon， 状态已经修改为已过期");
        }
        System.out.println("Timing task: Every ten seconds do CheckCouponStatusScheduledTask");
    }
}
